package com.yolo.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yolo.common.annotation.Log;
import com.yolo.common.enums.BusinessType;
import com.yolo.entity.*;
import com.yolo.entity.dto.SalaryDto;
import com.yolo.service.EmpSalaryService;
import com.yolo.service.SalaryService;
import com.yolo.util.Result;
import com.yolo.util.SalaryUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 霜蟾
 * @since 2021-04-26
 */
@RestController
@RequestMapping("/salary")
@CrossOrigin
public class SalaryController {
    @Autowired
    SalaryUtil salaryUtil;
    @Autowired
    EmpSalaryService empSalaryService;
    @Autowired
    SalaryService salaryService;

    @Log(title = "薪资模块",businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result batchSalary() {
        String month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM"));
        List<EmpSalary> list = empSalaryService.list();
        for (EmpSalary e : list) {
            if (e.getMonth().equals(month)) {
                return Result.succ("本月薪资已结算");
            }
        }
        salaryUtil.saveSalary();
        return Result.succ("结算成功");
    }

    @Log(title = "薪资模块",businessType = BusinessType.QUERY)
    @GetMapping("")
    public Result salaryList(SalaryDto salaryDto) throws ParseException {
        QueryWrapper<EmpSalary> qw = new QueryWrapper<>();
        String month;
        if (StringUtils.isEmpty(salaryDto.getMonth())) {
            month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM"));
        } else {
            DateFormat format = new SimpleDateFormat("yyyy-MM");
            Date date = format.parse(salaryDto.getMonth());
            date.setMonth(date.getMonth() + 1);
            month = format.format(date);
        }
        qw.eq("month", month);
        if (!StringUtils.isEmpty(salaryDto.getName())) {
            qw.like("name", salaryDto.getName());
        }
        IPage<EmpSalary> empSalaryIPage = new Page<>(salaryDto.getPageNo(), salaryDto.getPageSize());
        IPage<EmpSalary> page = empSalaryService.page(empSalaryIPage, qw);
        return Result.succ(MapUtil.builder()
                .put("data", page.getRecords())
                .put("count", page.getTotal())
                .map()
        );
    }

    @Log(title = "薪资模块",businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public Result delete(String ids) {
        String[] split = ids.split(",");
        salaryService.removeByIds(Arrays.asList(split));
        return Result.succ("删除成功");
    }

    @Log(title = "薪资模块",businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void exportDept(HttpServletResponse response) {
        try {
            String month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM"));
            List<EmpSalary> list = empSalaryService.list(new QueryWrapper<EmpSalary>().eq("month", month));
            @SuppressWarnings("resource")
            HSSFWorkbook wb = new HSSFWorkbook();
            //HSSFCellStyle style = ExcelStyleUtil.getStyle(wb);
            HSSFSheet sheet = wb.createSheet("记录");
            HSSFRow row;
            int columnIndex = 0;
            row = sheet.createRow(0);
            row.setHeight((short) (22.50 * 10));//设置行高
            row.createCell(columnIndex).setCellValue("序号");
            row.createCell(++columnIndex).setCellValue("员工编号");
            row.createCell(++columnIndex).setCellValue("员工名");
            row.createCell(++columnIndex).setCellValue("月份");
            row.createCell(++columnIndex).setCellValue("工作时间");
            row.createCell(++columnIndex).setCellValue("基本薪资");
            row.createCell(++columnIndex).setCellValue("出差补贴");
            row.createCell(++columnIndex).setCellValue("全勤");
            row.createCell(++columnIndex).setCellValue("税务");
            row.createCell(++columnIndex).setCellValue("罚款");
            row.createCell(++columnIndex).setCellValue("实发薪资");
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                EmpSalary entity = list.get(i);
                columnIndex = 0;
                row.createCell(columnIndex).setCellValue(i + 1);
                row.createCell(++columnIndex).setCellValue(entity.getEmpId());
                row.createCell(++columnIndex).setCellValue(entity.getName());
                row.createCell(++columnIndex).setCellValue(entity.getMonth());
                row.createCell(++columnIndex).setCellValue(entity.getWorkDate());
                row.createCell(++columnIndex).setCellValue(entity.getBaseSalary());
                row.createCell(++columnIndex).setCellValue(entity.getErrandSubsidys());
                row.createCell(++columnIndex).setCellValue(entity.getFullAttendance());
                row.createCell(++columnIndex).setCellValue(entity.getTax());
                row.createCell(++columnIndex).setCellValue(entity.getFine());
                row.createCell(++columnIndex).setCellValue(entity.getFinalSalary());

            }
            sheet.setDefaultRowHeight((short) (16.5 * 20));
            //列宽自适应
            for (int i = 0; i <= 11; i++) {
                sheet.autoSizeColumn(i);
            }

            String title = "czjl_all";
            response.setHeader("Content-disposition", "attachment;fileName=" + title + ".xls");
            response.setContentType("application/octet-stream;charset=utf-8");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
